package org.shell;

import java.util.Arrays;

public class ThreadsManager {

    public static String listThreads() {
        StringBuilder b = new StringBuilder();
        b.append(formatList(getList()));
        return b.toString();
    }

    public static boolean killThread(long id) {
        for(Thread t : getList()) {
            if(t.getId() == id) {
                t.interrupt();
                return true;
            }
        }
        return false;
    }

    private static String formatList(Thread[] threads) {
        StringBuilder output = new StringBuilder();
        int columnFirst = 7;
        for (Thread t : threads) {
            Long id = t.getId();
            String name = t.getName();
            int idLength = id.toString().length();
            output.append(id);
            for (int i = idLength; i < columnFirst; i++) {
                output.append(" ");
            }
            output.append(name);
            output.append("\n");
        }
        return output.toString();
    }

    private static Thread[] getList() {
        ThreadGroup root = Thread.currentThread().getThreadGroup().getParent();
        int count = root.activeCount();
        Thread threads[] = new Thread[count * 2];
        count = root.enumerate(threads, true);
        return Arrays.copyOfRange(threads, 0, count);
    }
}
